﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Management;
using System.Diagnostics;


namespace CronCommon
{

    public static class Dir
    {
        /// <summary>
        /// 检查应用需要的文件目录是不否存在,不存在创建
        /// </summary>
        public static void CheckDirectory()
        {
            List<string> Dlist = new List<string>();
            Dlist.Add($"{GetCurrentDirectory()}\\Log"); 
            Dlist.Add($"{GetCurrentDirectory()}\\template"); //模板文件目录
            Dlist.Add($"{GetCurrentDirectory()}\\exceltmp"); //生成后的临时文件目录
            Dlist.Add($"{GetCurrentDirectory()}\\bak");  //修改后的配置文件存放目录
            Dlist.Add($"{GetCurrentDirectory()}\\SendRetry"); //邮件发送送败后的重试目录

            foreach (var tmp in Dlist)
            {
                if (!Directory.Exists(tmp)) Directory.CreateDirectory(tmp); 
            }
            Dlist = null;
        }

        /// <summary>
        /// 取程序当前目录路径
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentDirectory()
        {
            return Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
        }

        /// <summary>
        /// 取当前程序的文件名
        /// </summary>
        /// <returns>文件名</returns>
        public static string GetCurrentFilename()
        {
            string str = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
            return Path.GetFileName(str);

        }

        /// <summary>
        /// 取当前程序的文件名,不含文件扩展名.
        /// </summary>
        /// <returns>文件名</returns>
        public static string GetCurrentFilenameWithoutExtension()
        {
            string str = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
            return Path.GetFileNameWithoutExtension(str);
        }

        /// <summary>
        /// 返回程序当前的第1个参数，参数0为程序名
        /// </summary>
        /// <returns></returns>
        public static string GetCommandLineArgs()
        {
            string[] arg = Environment.GetCommandLineArgs();
            return arg.Length>1?arg[1].ToUpper():null;
        }

        /// <summary>
        /// 取当前任务的所有日志文件名清单
        /// </summary>
        /// <param name="cronid">任务ID</param>
        /// <returns>文件列表</returns>
        public static string[] GetLogFileList(string cronid)
        {
            return Directory.GetFiles($"{GetCurrentDirectory()}\\log", $"*{cronid}.log");
        }

        public static string[] GetLogFileList(DateTime logdate)
        {
            return Directory.GetFiles($"{GetCurrentDirectory()}\\log", $"{logdate.ToString("yyyyMMdd")}*.log");
        }
    }

    public static class Log
    {
        /// <summary>
        /// 记录写入日志
        /// </summary>
        /// <param name="text">记录的文本</param>
        public static void Writter(string text)
        {
            if (!Directory.Exists($"{Dir.GetCurrentDirectory()}\\Log")) Directory.CreateDirectory($"{Dir.GetCurrentDirectory()}\\Log");

            string cronid = Dir.GetCommandLineArgs();

            string logPath;
            if (string.IsNullOrWhiteSpace(cronid))
            {
                logPath = $"{Dir.GetCurrentDirectory()}\\Log\\{DateTime.Now.ToString("yyyyMMdd")}_{Dir.GetCurrentFilenameWithoutExtension()}.log";
            }
            else
            {
                logPath = $"{Dir.GetCurrentDirectory()}\\Log\\{DateTime.Now.ToString("yyyyMMdd")}_{Dir.GetCurrentFilenameWithoutExtension()}_{cronid}.log";
             //   text=string.Concat(cronid," ", text);
            }

            if (File.Exists(logPath))
            {
                FileInfo fileinfo = new FileInfo(logPath);
            }
            FileStream fs = new FileStream(logPath, FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            m_streamWriter.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] {text}");
            m_streamWriter.Flush();
            m_streamWriter.Close();
            fs.Close();
        }

        public static void Writter(string appname,string text)
        {
            if (!Directory.Exists($"{Dir.GetCurrentDirectory()}\\Log")) Directory.CreateDirectory($"{Dir.GetCurrentDirectory()}\\Log");

            string cronid = appname;

            string logPath;
            if (string.IsNullOrWhiteSpace(cronid))
            {
                logPath = $"{Dir.GetCurrentDirectory()}\\Log\\{DateTime.Now.ToString("yyyyMMdd")}_{Dir.GetCurrentFilenameWithoutExtension()}.log";
            }
            else
            {
                logPath = $"{Dir.GetCurrentDirectory()}\\Log\\{DateTime.Now.ToString("yyyyMMdd")}_{Dir.GetCurrentFilenameWithoutExtension()}_{cronid}.log";
                //   text=string.Concat(cronid," ", text);
            }

            if (File.Exists(logPath))
            {
                FileInfo fileinfo = new FileInfo(logPath);
            }
            FileStream fs = new FileStream(logPath, FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            m_streamWriter.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] {text}");
            m_streamWriter.Flush();
            m_streamWriter.Close();
            fs.Close();
        }
    }

    public static class RetrySendMailRecord
    {
        public static void CronIdRedord(CronStruct cs)
        {
            string SendRetryFilename = $"{ Dir.GetCurrentDirectory()}\\SendRetry\\{cs.SN}.txt";
            Int32 rccount = 0;
            if (File.Exists(SendRetryFilename))
            {
                string str = null;
                using (StreamReader streamReader = new StreamReader(SendRetryFilename, Encoding.GetEncoding("GB2312")))
                {
                    str = streamReader.ReadLine();
                    if (str == null)
                    {
                        Log.Writter("读取重发文件记录出错");
                        return;
                    }
                    Log.Writter("重发记录配脚本" + str);
                    string[] tempcount = str.Split(' ');
                    Log.Writter(tempcount.Count().ToString());
                    rccount = Convert.ToInt32(tempcount[3]);
                }

                if (rccount <= 1)
                {
                    File.Delete(SendRetryFilename);
                    return;
                }
            }

            FileStream fs = new FileStream(SendRetryFilename, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
            StreamWriter m_streamWriter = new StreamWriter(fs, Encoding.GetEncoding("GB2312"));
            if (rccount == 0) rccount = cs.失败重试次数;
            else rccount = rccount - 1;

            m_streamWriter.WriteLine($"{DateTime.Now.AddMinutes(cs.重试间隔分钟).ToString("yyyyMMdd-HH:mm")} {System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName} {cs.SN} {rccount.ToString()}");
            m_streamWriter.Flush();
            m_streamWriter.Close();
            fs.Close();

        }
        public static void CronIdRedord(string cronid)
        {
            string SendRetryFilename = $"{ Dir.GetCurrentDirectory()}\\SendRetry\\{cronid}.txt";
            Int32 rccount = 0;
            if (File.Exists(SendRetryFilename))
            {
                string str = null;
                using (StreamReader streamReader = new StreamReader(SendRetryFilename, Encoding.GetEncoding("GB2312")))
                {
                    str = streamReader.ReadLine();
                    if (str == null)
                    {
                        Log.Writter("读取重发文件记录出错");
                        return;
                    }
                    Log.Writter("重发记录配脚本" + str);
                    string[] tempcount = str.Split(' ');
                    Log.Writter(tempcount.Count().ToString());
                    rccount = Convert.ToInt32(tempcount[3]);
                }

                if (rccount <= 1)
                {
                    File.Delete(SendRetryFilename);
                    return;
                }
            }

            FileStream fs = new FileStream(SendRetryFilename, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
            StreamWriter m_streamWriter = new StreamWriter(fs, Encoding.GetEncoding("GB2312"));
            if (rccount == 0) rccount = 10;
            else rccount = rccount - 1;

            m_streamWriter.WriteLine($"{DateTime.Now.AddMinutes(15).ToString("yyyyMMdd-HH:mm")} {System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName} {cronid} {rccount.ToString()}");
            m_streamWriter.Flush();
            m_streamWriter.Close();
            fs.Close();

        }

    }

}
